﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iTunesLib;
using System.IO;
using iTunesFastForward.Properties;

namespace iTunesFastForward
{
    public partial class iTunesPCForm : Form
    {

        m3uCreator creator;
        Dictionary<string, IITPlaylist> playlists;

        #region Properties
        public string SelectedPath
        {
            get
            {
                return iTFFSettings.Instance.PCexportTo;
            }
            set
            {
                if (Directory.Exists(value))
                {
                    pathTextBox.Text = value;
                    outputDirFolderBrowserDialog.SelectedPath = value;
                    creator.OutputDir = new DirectoryInfo(value);
                    iTFFSettings.Instance.PCexportTo = value;
                }
            }
        }

        public bool ReplaceiTunesPath
        {
            get
            {
                return iTFFSettings.Instance.PCreplaceItunesPath;
            }
            set
            {
                iTFFSettings.Instance.PCreplaceItunesPath = value;
                replaceCheckBox.Checked = value;
            }
        }

        public string iTunesPath
        {
            get
            {
                return iTFFSettings.Instance.PCitunesPath;
            }

            set
            {
                if (Directory.Exists(value))
                {
                    itunesPathTextBox.Text = value;
                    iTFFSettings.Instance.PCitunesPath = value;
                }
            }
        }

        public string ReplacementString
        {
            get
            {
                return iTFFSettings.Instance.PCreplacementString;
            }

            set
            {
                iTFFSettings.Instance.PCreplacementString = value;
                replacementStringTextBox.Text = value;
            }
        }


        public string[] SelectedPlaylists
        {
            get
            {
                if (iTFFSettings.Instance.PCselectedPlaylists == null)
                    return new string[] { };
                return iTFFSettings.Instance.PCselectedPlaylists.Split('\t');
            }
            set
            {
                iTFFSettings.Instance.PCselectedPlaylists = string.Join("\t", value);
                // déselectionner tout
                PlaylistsUnCheckAll();

                // resélectionner ce qu'il faut
                playlistsCheckedListBox.BeginUpdate();
                foreach (var pl in value)
                {
                    int index = playlistsCheckedListBox.FindStringExact(pl);
                    if (index != -1)
                        playlistsCheckedListBox.SetItemChecked(index, true);
                }
                playlistsCheckedListBox.EndUpdate();
            }
        } 
        #endregion

        #region Init and Leave
        public iTunesPCForm()
        {
            creator = new m3uCreator();
            playlists = new Dictionary<string, IITPlaylist>();
            InitializeComponent();
        }

        private void iTunesPCForm_Load(object sender, EventArgs e)
        {
            foreach (IITPlaylist pl in iTunesActions.Instance.GetPlaylists()) // protégé
            {
                playlists[pl.Name] = pl;
                playlistsCheckedListBox.Items.Add(pl.Name);
            }

            // restaurer l'état précédent

            // itunes path
            if (string.IsNullOrEmpty(iTunesPath))
                iTunesPath = iTunesActions.Instance.GetITunesFolder(); // protégé
            else
                iTunesPath = iTunesPath;

            // selected path
            if (string.IsNullOrEmpty(SelectedPath))
                SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
            else
                SelectedPath = SelectedPath;

            // repalce checkbox
            ReplaceiTunesPath = ReplaceiTunesPath;

            // replacement path
            ReplacementString = ReplacementString;

            // playlists
            SelectedPlaylists = SelectedPlaylists;

        }

        #endregion

        #region Folder browser dialogs
        private void browseExportToButton_Click(object sender, EventArgs e)
        {
            if (outputDirFolderBrowserDialog.ShowDialog() == DialogResult.OK)
                SelectedPath = outputDirFolderBrowserDialog.SelectedPath;
        }

        private void browseiTunesPathbutton_Click(object sender, EventArgs e)
        {
            if (iTunesPathFolderBrowserDialog.ShowDialog() == DialogResult.OK)
                iTunesPath = iTunesPathFolderBrowserDialog.SelectedPath;
        } 
        #endregion

        #region Export behavior
        List<IITPlaylist> selectedPlaylists;
        private void exportButton_Click(object sender, EventArgs e)
        {

            if (!Directory.Exists(SelectedPath))
                Utils.ShowErrorMessage("Please first select a folder.", "");
            else if (playlistsCheckedListBox.CheckedIndices.Count == 0)
                Utils.ShowErrorMessage("Please select at least one playlist.", "");
            else
            {
                exportButton.Enabled = false;
                exportButton.Text = "Exporting...";
                exporProgressBar.Visible = true;
                playlistsCheckedListBox.Enabled = false;

                selectedPlaylists = new List<IITPlaylist>();
                foreach (var plName in playlistsCheckedListBox.CheckedItems)
                    selectedPlaylists.Add(playlists[((string)plName)]);

                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int i = 0;
            foreach (var currentPlaylist in selectedPlaylists)
            {

                List<string> trackPath = new List<string>();
                foreach (IITTrack track in currentPlaylist.Tracks)
                {
                    if (track.Kind == ITTrackKind.ITTrackKindFile)
                    {
                        IITFileOrCDTrack fileTrack = (IITFileOrCDTrack)track;

                        string p;
                        if (replaceCheckBox.Checked)
                            p = replacementStringTextBox.Text + fileTrack.Location.Replace(itunesPathTextBox.Text, string.Empty).Remove(0, 1); // supprimer le /
                        else
                            p = fileTrack.Location;

                        trackPath.Add(p);
                    }
                }

                creator.CreatePlaylist(currentPlaylist.Name, trackPath.ToArray());
                backgroundWorker1.ReportProgress((int)((float)++i / selectedPlaylists.Count * 100), i);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            exportButton.Enabled = true;
            exportButton.Text = "Export!";
            playlistsCheckedListBox.Enabled = true;
            exporProgressBar.Visible = false;
        }


        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            exporProgressBar.Value = e.ProgressPercentage;
            exportButton.Text = string.Format("Exporting... {0} of {1}", (int)e.UserState, selectedPlaylists.Count);
        } 
        #endregion

        #region Right part settings management
        private void replaceCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            itunesPathTextBox.Enabled = replaceCheckBox.Checked;
            browseiTunesPathbutton.Enabled = replaceCheckBox.Checked;
            replacementStringTextBox.Enabled = replaceCheckBox.Checked;

            ReplaceiTunesPath = replaceCheckBox.Checked;
        }

        private void pathTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (Directory.Exists(pathTextBox.Text))
                SelectedPath = pathTextBox.Text;
            else
                pathTextBox.Undo();
        }

        private void itunesPathTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (Directory.Exists(itunesPathTextBox.Text))
                iTunesPath = itunesPathTextBox.Text;
            else
                itunesPathTextBox.Undo();
        }

        private void replacementStringTextBox_TextChanged(object sender, EventArgs e)
        {
            ReplacementString = replacementStringTextBox.Text;
        } 
        #endregion

        #region CheckedListBow for playlists Management
        private void selectALbutton_Click(object sender, EventArgs e)
        {
            playlistsCheckedListBox.BeginUpdate();
            for (int i = 0; i < playlistsCheckedListBox.Items.Count; i++)
            {
                playlistsCheckedListBox.SetItemChecked(i, true);
            }
            playlistsCheckedListBox.EndUpdate();
        }

        private void unSelectALLbutton_Click(object sender, EventArgs e)
        {
            PlaylistsUnCheckAll();
        }

        private void PlaylistsUnCheckAll()
        {
            playlistsCheckedListBox.BeginUpdate();
            for (int i = 0; i < playlistsCheckedListBox.Items.Count; i++)
            {
                playlistsCheckedListBox.SetItemChecked(i, false);
            }
            playlistsCheckedListBox.EndUpdate();
        }

        private void playlistsCheckedListBox_KeyDown(object sender, KeyEventArgs e)
        {
            // manger la key
            e.Handled = true;
            e.SuppressKeyPress = true;
        }

        private void playlistsCheckedListBox_MouseUp(object sender, MouseEventArgs e)
        {
            string[] pl = new string[playlistsCheckedListBox.CheckedIndices.Count];

            for (int i = 0; i < pl.Length; i++)
                pl[i] = (string)playlistsCheckedListBox.Items[playlistsCheckedListBox.CheckedIndices[i]];

            SelectedPlaylists = pl;
        } 
        #endregion

    }
}
